'use strict'

var appControllers = angular.module('appControllers', []);

appControllers.controller('indexCtrl', ['$cookies', '$scope', '$http', '$location', 'messageService', '$timeout',
    function ($cookies, $scope, $http, $location, messageService, $timeout){
        $scope.name = $cookies['name'];
        $scope.messages = messageService.messageList;

        $scope.logout = function(){
            $http.post('/logout').success(function(data){
                messageService.addMessage(data.code, data.msg);
                $scope.name = '';
                $location.url('/');
            });
        };

        //搜索
        $scope.timer = null;
        $scope.resultBoxShow = false;
        $scope.search = function () {
            if($scope.timer){
                $timeout.cancel($scope.timer);
            }
            $scope.timer = $timeout(function () {
                if($scope.keyword){
                    $http.post('/search', {keyword: $scope.keyword}).success(function (data) {
                        if(data.code){
                            $scope.usersSearched = data.result.users.length > 0 ?  data.result.users : null;
                            $scope.postsSearched = data.result.posts.length > 0 ? data.result.posts : null;
                            $scope.resultBoxShow = true;
                        } else {
                            messageService.addMessage(data.code, data.msg);
                        }
                    });
                } else {
                    $scope.resultBoxShow = false;
                }
            }, 800);
        };
        $scope.showResultBox = function(){
            if($scope.keyword && $scope.keyword.length > 0){
                $scope.resultBoxShow = true;
            }
        };
        $scope.hideResultBox = function(){
            $timeout(function () {
                $scope.resultBoxShow = false;
            }, 300);
        };

        $scope.$on('login', function (e, d) {
            $scope.name = d;
        });

        $scope.$on('logout', function (e, d) {
            $scope.name = '';
        });
    }
]);

/**
 * 特定id的post
 */
appControllers.controller('specificCtrl', ['$scope', '$http', '$cookies', '$routeParams', 'messageService',
    function($scope, $http, $cookies, $routeParams, messageService){
        $scope.name = $cookies['name'];
        $scope.isCollapsed = true;

        $http.post('/post', {postId: $routeParams.postId}).success(function (data) {
            if(data.code){
                $scope.post = data.post;
            } else {
                messageService.addMessage(data.code, data.msg);
            }
        });
    }
]);


/**
 * 文章列表控制器
 */
appControllers.controller('postsCtrl', ['$cookies', '$scope', '$http', '$location', '$routeParams', 'postsService', 'messageService',
	function ($cookies, $scope, $http, $location, $routeParams, postsService, messageService){
        $scope.hot = "";
        //热门页面
        if($location.url().indexOf('hot') > 0){
            $scope.hot = "最热门秘密";
        }
        //特定标签页面
        $scope.tag = "";
        if($location.url().indexOf('tag') > 0){
            $scope.tag = $routeParams.tag;
        }
        $scope.name = $cookies['name'];
		$scope.isCollapsed = true;
		$scope.start = 0;
		$scope.pageNumber = 5;
		$scope.loader = '加载更多';

		postsService.getPosts('', $scope.start, $scope.pageNumber, $scope.hot, $scope.tag, function(data){
            if(data.code){
                $scope.posts = data.posts;
				$scope.tags = data.tags;
                $scope.start += $scope.pageNumber;
            } else {
                messageService.addMessage(data.code, data.msg);
            }
		});

		$scope.loadMore = function (){
			if($scope.loader == '到底啦~'){
				return ;
			}

			postsService.getPosts('', $scope.start, $scope.pageNumber, $scope.hot, $scope.tag, function(data){
				if(data.posts.length > 0){
					$scope.posts = $scope.posts.concat(data.posts);
					$scope.start += data.posts.length;
                    if(data.length < 5){
                        $scope.loader = '到底啦~';
                    }
				} else {
					$scope.loader = '到底啦~';
				}
			});
		};

		$scope.vote = function(post){
			$http.post('/vote', {cid: post._id, votes: post.good }).success(function (data){
				if(data.code){
					post.good += 1;
				}
			});
		};
}]);

/**
 * 登录
 */
appControllers.controller('loginCtrl', ['$scope', '$http', '$location', '$rootScope', 'userService', 'messageService',
	function ($scope, $http, $location, $rootScope, userService, messageService){
		$scope.form = {};
		$scope.form.submit = function () {
			if($('.ng-invalid').length > 0){
				return false;
			}
			userService.login($scope.form, function (data){
                messageService.addMessage(data.code, data.msg);
                if(data.code){
                    $rootScope.$broadcast('login', data.user.name);
                    $location.url('/');
                }
			});
		};
}]);

/**
 * 注册
 */
appControllers.controller('registCtrl', ['$scope', '$http', '$location', 'userService', 'messageService',
	function ($scope, $http, $location, userService, messageService){
		$scope.form = {};  //创建一个名为form 的NG 对象

		$scope.form.submit = function () {
			if($('.ng-invalid').length > 0){
				return false;
			} 

			userService.regist($scope.form, function (data){
                messageService.addMessage(data.code, data.msg);
                if(data.code){
                    $location.url('/login');
                }
			});
		};
}]);

/**
 * 发布
 */
appControllers.controller('sayCtrl', ['$scope', '$http', '$location', 'messageService', function ($scope, $http, $location, messageService){
	$scope.form = {};

	$scope.form.submit = function(){
		$scope.form.content = $('#editor').val();
		if($scope.form.content.length < 10){
			messageService.addMessage(0, '内容太短啦，请至少输入10个字~');
            return false;
		}
        if(!$scope.form.sc || $scope.form.sc.length !== 6){
            messageService.addMessage(0, '请输入6位的验证码~');
            return false;
        }
		$http.post('/say', $scope.form).success(function (data){
			messageService.addMessage(data.code, data.msg);
            if(data.code){
                $location.url('/');
            }
		});
	};
}]);

/**
 * 个人主页
 */
appControllers.controller('homeCtrl', ['$scope', '$http', '$routeParams', 'postsService', '$cookies', 'messageService',
	function ($scope, $http, $routeParams, postsService, $cookies, messageService){
        //现在登录的用户
		$scope.userNow = $cookies['name'];
		//主页的主人
		$scope.name = $routeParams.user;
		$scope.isCollapsed = true;
		$scope.start = 0;
		$scope.pageNumber = 5;
		$scope.loader = '加载更多';
		//获取当前主页的主人的posts
		postsService.getPosts($scope.name, $scope.start, $scope.pageNumber, null, null, function(data){
            if(data.code){
                $scope.posts = data.posts;
                $scope.start += $scope.pageNumber;
            } else {
                messageService.addMessage(data.code, data.msg);
            }
		});
		//删除post
		$scope.deletePost = function (index) {

			if(window.confirm('你确定要删除吗？')){
				$http.post('/deletePost', {id: $scope.posts[index]._id}).success(function (data) {
                    messageService.addMessage(data.code, data.msg);
					if(data.code){
                        $scope.posts.splice(index, 1);
                    }
				});
			} else {
				return ;
			}
		};
		//加载更多
		$scope.loadMore = function (){
			if($scope.loader == '到底啦~'){
				return ;
			}
			postsService.getPosts($scope.name, $scope.start, $scope.pageNumber, null, null, function(data){
                if(data.posts.length > 0){
                    $scope.posts = $scope.posts.concat(data.posts);
                    $scope.start += data.posts.length;
                    if(data.length < 5){
                        $scope.loader = '到底啦~';
                    }
                } else {
                    $scope.loader = '到底啦~';
                }
			});
		};

		$scope.form = {};
		$scope.form.submit = function(){
			$scope.form.content = $('#editor').val();
			$scope.form.postId = $('#postId').val();
			$http.post('/editPost', $scope.form).success(function(data){
                messageService.addMessage(data.code, data.msg);
				window.location.reload();
			});
		};
	}
]);

/**
 * 账号设置页
 */
appControllers.controller('settingsCtrl', ['$scope', '$http', '$routeParams', '$location','$anchorScroll', '$timeout', '$rootScope', '$upload', 'messageService',
	function ($scope, $http, $routeParams, $location, $anchorScroll, $timeout, $rootScope, $upload, messageService){
		$scope.name = $routeParams.user;
		$scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);

		$http.post('/getUserInfo', {name: $scope.name}).success(function (data){
			if(data.code){
				data.user.avatar +="?sid="+ Date.now(); 
				$scope.user = data.user;
			} else {
                messageService.addMessage(data.code, data.msg);
				$location.url('/');
			}
		});

		//确认选择的是图片并返回图片base64编码预览
		$scope.generateThumb = function(file) {
			if (file != null) {
				if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
					$timeout(function() {
						var fileReader = new FileReader();
						fileReader.readAsDataURL(file);
						fileReader.onload = function(e) {
							$timeout(function() {
								file.dataUrl = e.target.result;
							});
						}
					});
				}
			}
		};
		//修改头像
		$scope.updateAvatar = function (avatar) {
			if (avatar) {
				console.log("upload");
				var file = avatar[0];
				$upload.upload({
					url: '/updateAvatar',
					fields: {
						'name': $scope.name
					},
					file: file
				}).progress(function (evt) {
					var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
					console.log('progress: ' + progressPercentage + '% ' +
					evt.config.file.name);
				}).success(function (data, status, headers, config) {
					console.log('file ' + config.file.name + ' uploaded.');
					$scope.user.avatar = $scope.avatar[0].dataUrl;
					//替换成一个透明图片 1 * 1 px
					$scope.avatar[0].dataUrl = '';
                    messageService.addMessage(data.code, data.msg);
				});
			}
		};

		/**
		 * 修改昵称，暂时不用
		 * @param oldName
		 * @param newName
		 * @returns {boolean}

		$scope.updateName = function (oldName, newName) {
			if($('.ng-invalid').length > 0){
				return false;
			}
			console.log(oldName+ newName);
			if(oldName == $scope.user.name){
				if(oldName == newName){
					return false;
				} else {
					$http.post('/updateName', {name: oldName, newName: newName}).success(function (data) {
						alert(data.msg);
					});
				}
			}
		}
		 */

		//修改邮箱
		$scope.updateEmail = function (oldEmail, newEmail) {
			if($('.ng-invalid').length > 0){
				return false;
			}
			if(oldEmail == $scope.user.email){
				if(newEmail == oldEmail){
                    messageService.addMessage(0, '新旧邮箱不能相同~');
					return false;
				} else {
					$http.post('/updateEmail', {name: $scope.name, email: newEmail}).success(function (data) {
                        messageService.addMessage(data.code, data.msg);
                        if(data.code){
                            $scope.newEmail = '';
                            $scope.oldEmail = '';
                        }
					});
				}
			}
		};

		//修改密码
		$scope.updatePwd = function (oldPwd, newPwd) {
			if($('.ng-invalid').length > 0){
				return false;
			}
			if(newPwd == oldPwd){
                messageService.addMessage(0 , '新旧密码不能相同~');
				$scope.pwd1 = '';
				return ;
			} else {
				$http.post('/updatePwd', {name: $scope.name, oldPwd: oldPwd,newPwd: newPwd}).success(function (data) {
                    messageService.addMessage(data.code, data.msg);
                    if(data.code){
                        messageService.addMessage(data.code, '请重新登录~');

                        $rootScope.$broadcast('logout');

                        $location.url('/login');
                    }
				});
			}
		};
	}
]);